var express = require("express");
var app = express();


app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


var server = require("http").createServer(app);

var io =require("socket.io")(server);

//var BigNumber = require('bignumber.js');

const { keccak256, ecsign,isValidPrivate,privateToPublic} = require('ethereumjs-util')


app.use(express.static("public"));//public路径下面配置静态文件的路径，这里可以放html页面及其它相关的前端所用的js文件

var Web3= require("Web3");

Web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));


var abi = [
    {
      "constant": true,
      "inputs": [
        {
          "name": "",
          "type": "bytes32"
        }
      ],
      "name": "mapNicknameByAddr",
      "outputs": [
        {
          "name": "",
          "type": "address"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [],
      "name": "owner",
      "outputs": [
        {
          "name": "",
          "type": "address"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [
        {
          "name": "",
          "type": "uint256"
        }
      ],
      "name": "videos",
      "outputs": [
        {
          "name": "id",
          "type": "uint256"
        },
        {
          "name": "title",
          "type": "string"
        },
        {
          "name": "owner",
          "type": "address"
        },
        {
          "name": "buyer",
          "type": "address"
        },
        {
          "name": "hashcode",
          "type": "string"
        },
        {
          "name": "value",
          "type": "uint256"
        },
        {
          "name": "isSell",
          "type": "bool"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "inputs": [],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "constructor"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "name": "_from",
          "type": "address"
        },
        {
          "indexed": true,
          "name": "_to",
          "type": "address"
        },
        {
          "indexed": false,
          "name": "_value",
          "type": "uint256"
        }
      ],
      "name": "Transfer",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "name": "_from",
          "type": "address"
        },
        {
          "indexed": false,
          "name": "nickname",
          "type": "string"
        }
      ],
      "name": "onRegistFree",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "name": "_from",
          "type": "address"
        },
        {
          "indexed": false,
          "name": "hashcode",
          "type": "string"
        }
      ],
      "name": "onUploadVideo",
      "type": "event"
    },
    {
      "anonymous": false,
      "inputs": [
        {
          "indexed": true,
          "name": "_owner",
          "type": "address"
        },
        {
          "indexed": true,
          "name": "_buyer",
          "type": "address"
        },
        {
          "indexed": false,
          "name": "hashcode",
          "type": "string"
        }
      ],
      "name": "onBuyVideo",
      "type": "event"
    },
    {
      "constant": true,
      "inputs": [],
      "name": "getVIndex",
      "outputs": [
        {
          "name": "",
          "type": "uint256"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": false,
      "inputs": [
        {
          "name": "title",
          "type": "string"
        },
        {
          "name": "addr",
          "type": "address"
        },
        {
          "name": "hashcode",
          "type": "string"
        },
        {
          "name": "value",
          "type": "uint256"
        }
      ],
      "name": "uploadVideo",
      "outputs": [
        {
          "name": "",
          "type": "bool"
        }
      ],
      "payable": true,
      "stateMutability": "payable",
      "type": "function"
    },
    {
      "constant": false,
      "inputs": [
        {
          "name": "vid",
          "type": "uint256"
        }
      ],
      "name": "buyVideo",
      "outputs": [],
      "payable": true,
      "stateMutability": "payable",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [],
      "name": "boughtVids",
      "outputs": [
        {
          "name": "",
          "type": "uint256[]"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [
        {
          "name": "vid",
          "type": "uint256"
        }
      ],
      "name": "getVideoById",
      "outputs": [
        {
          "name": "",
          "type": "uint256"
        },
        {
          "name": "",
          "type": "string"
        },
        {
          "name": "",
          "type": "address"
        },
        {
          "name": "",
          "type": "address"
        },
        {
          "name": "",
          "type": "string"
        },
        {
          "name": "",
          "type": "uint256"
        },
        {
          "name": "",
          "type": "bool"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": false,
      "inputs": [
        {
          "name": "nickname",
          "type": "string"
        },
        {
          "name": "passpwd",
          "type": "uint256"
        }
      ],
      "name": "registByFree",
      "outputs": [],
      "payable": true,
      "stateMutability": "payable",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [
        {
          "name": "nickname",
          "type": "string"
        },
        {
          "name": "passpwd",
          "type": "uint256"
        }
      ],
      "name": "loginByPwd",
      "outputs": [
        {
          "name": "",
          "type": "bool"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": true,
      "inputs": [
        {
          "name": "addr",
          "type": "address"
        }
      ],
      "name": "getBalance",
      "outputs": [
        {
          "name": "",
          "type": "uint256"
        }
      ],
      "payable": false,
      "stateMutability": "view",
      "type": "function"
    },
    {
      "constant": false,
      "inputs": [
        {
          "name": "receiver",
          "type": "address"
        },
        {
          "name": "amount",
          "type": "uint256"
        }
      ],
      "name": "sendCoin",
      "outputs": [
        {
          "name": "sufficient",
          "type": "bool"
        }
      ],
      "payable": false,
      "stateMutability": "nonpayable",
      "type": "function"
    }
  ];
  
  
var address = "0x4693795c3CaA563Ff27157284EFF1f93D91E121A";


var ethTube = Web3.eth.contract(abi).at(address);

var address_owner = "0x3e80048f9a442a92799e0cf83a77f3f60dae8fa0";

//-----------------------------接口-------------------------------------

app.get("/registByFree",function(req,res){

	var nickname = req.query.nickname;

	var pwd = req.query.pwd;



	//var hexNickname = '0x' + keccak256(nickname).toString('hex');

	//console.log(hexNickname);

	var result = ethTube.registByFree.sendTransaction(nickname,pwd,{from:address_owner,gas:4712387});

	

	var userInfo =  {
	"result":result,
    "nickname": nickname
   }

	res.send(userInfo);


}

);



	var event = ethTube.onRegistFree({_from:address},{fromBlock: 0, toBlock: 'latest'});

	event.watch(function(error, result){
		console.log("watchonRegistFree_error:"+error);

		if (!error){
			 console.log("watchonRegistFree_result:"+result);
		}

	});

app.get("/getPwd",function(req,res){
	var addr = req.query.addr;


	var returnValue = ethTube.getPwdByAddr.call(addr);
    console.log(returnValue);
	
	
	
	var userInfo =  {
	"result":returnValue,
    "nickname": "aaa"
   }

	res.send(userInfo);


});
app.get("/loginByPwd",function(req,res){
	var nickname = req.query.nickname;
  console.log(nickname);
	var pwd = req.query.pwd;

    var hexPwd = '0x' + keccak256(pwd).toString('hex');
    console.log(hexPwd);


	var returnValue = ethTube.loginByPwd.call(nickname,pwd);
    console.log(returnValue);
	
	
	
	var userInfo =  {
	"result":returnValue,
    "nickname": nickname
   }

	res.send(userInfo);


});

//获取用户的eth地址
app.get("/getUserInfo",function(req,res){

	try{
		var nickname = req.query.nickname;
		var hexNickname = '0x' + keccak256(nickname).toString('hex');
		console.log("hexNickname:"+hexNickname);
		var returnValue = ethTube.mapNicknameByAddr.call(hexNickname); 
		console.log("returnValue:"+returnValue);
		var userInfo =  {
		"result":true,
		"address": returnValue
	   }
		
	}catch(e){

		console.log(e);
		
		var userInfo =  {
		"result":false
	   }
	}

	
	res.send(userInfo);
	

});


//打赏
app.get("/reward",function(req,res){


	var address = req.query.address;

	var amount = req.query.amount;

	var returnValue = ethTube.reward.call(address,amount).toString();

	   var result =  {
		"result":true,
		"hash": "0x3e80048f9a442a92799e0cf83a77f3f60dae8fa0"
	   }

	res.send(returnValue);

});



app.get("/listMining",function(req,res){

    var index = ethTube.getVIndex.call();
    var indexValue = index.c[0];
	console.log(indexValue);

	let arr=[];
	for ( var id = 1; id <=indexValue; id++){
	
		var video = ethTube.getVideoById.call(id);
		console.log(video);
	
		if(video[6]==false){
				var detail =  {
				"id": video[0].c[0],
				"title": video[1],
				"owner":video[2],
				"buyer":video[3],
				"hashcode":"",
				"value": video[5].c[0],
				"isSell":video[6]
				
			  }
			
		arr.push(detail);
		}
	
	}

	
	res.send(arr);
});


app.get("/listHot",function(req,res){
	
	var idList = ethTube.boughtVids.call();
	let myArray=[1];
    
   
	for ( var i = 0; i <myArray.length; i++){
		var id  = myArray[i];
		var video = ethTube.getVideoById.call(id);
		console.log(video);
		myArray.push(video);
	}
	
	return myArray;



});

app.get("/publishVideo",function(req,res){
	var addr = req.query.addr;

	var hashcode = req.query.hashcode;

	var value = req.query.value;

	var title = req.query.title;

	console.log("param:"+addr+","+hashcode+","+value+","+title)

	var returnValue = ethTube.uploadVideo.sendTransaction(title,addr,hashcode,value,{from:address_owner,gas:4712387});


	var event = ethTube.onUploadVideo({_from:Web3.eth.coinbase},{fromBlock: 0, toBlock: 'latest'});

	event.watch(function(error, result){
		console.log(error);
		console.log(result);
	});


	res.send(returnValue);
});


app.get("/buyVideo",function(req,res){

	var addr = req.query.addr;

	var vid = req.query.vid;

    var returnValue = ethTube.buyVideo.sendTransaction(vid,{from:addr,gas:4712387});

res.send(returnValue);

});

//视频详情
app.get("/videoDetail",function(req,res){

	var id = req.query.id;

	var video = ethTube.getVideoById.call(id);
		console.log(video);
	
			var detail =  {
				"id": video[0].c[0],
				"title": video[1],
				"owner":video[2],
				"buyer":video[3],
				"hashcode":"",
				"value": video[5].c[0],
				"isSell":video[6]
				
			  }
	
		if(video[6]==true){

			  detail.hashcode=video[4];
		
		}
  
 res.send(detail);
});


//获取余额
app.get("/getAccount",function(req,res){

	var nickname = req.query.nickname;


});





//-------------------------------------------------------------------------------------------

app.get("/getBalance",function(req,res){

	var address = req.query.address;

	var returnValue = ethTube.getBalance.call(address).toString();

	res.send(returnValue);


}

);




app.get("/sendcoin",function(req,res){

	var address_a = req.query.address_a;

	var address_b = req.query.address_b;

	var trans_value = req.query.trans_value;

	var txhash = ethTube.sendCoin.sendTransaction(address_b,trans_value,{from:address_a,gas:100000});

	res.send(txhash);
});


app.get("/",function(req,res){

	console.log(__dirname);
	res.sendFile(__dirname+"/index.html");

})

server.listen(2333, function () {
  console.log('App listening on port 2333, Please visit http://localhost:2333');
});
